import { ReactElement, useRef, useState, useEffect, RefObject } from 'react'
import { Form, Input, Row, Col, Space, Button, FormInstance, TreeSelect, Select } from 'antd'
import { History, Location } from 'history'
import style from './index.module.less'
import { ConditionSchema } from '@src/components/schema/condition'
import { setSearch, getSearch, awaitWrap } from '@src/assets/js/tool'
import { DataNode } from 'rc-tree-select/lib/interface'
import moment, { Moment } from 'moment'
import { getTreeRequest, getOccupation, getPersonList } from './ajax'
import qs from 'query-string';

const { Item } = Form
const { Option } = Select

export function formatCondition (d: { [k: string]: any }): ConditionSchema[] {
  const r: ConditionSchema[] = []
  if (typeof d.year === 'string') {
    if (/^\d+$/.test(d.year)) {
      r.push({ k: 'caseon.year', o: '=', v: d.year })
    }
  } else {
    r.push({ k: 'caseon.year', o: '=', v: moment().year() })
  }
  if (typeof d.name === 'string' && d.name.length > 0) {
    r.push({ k: 'a.name', o: 'like', v: `%${d.name}%` })
  }
  if (typeof d.cause_action === 'string' && d.cause_action.length > 0) {
    r.push({ k: 'ca.cause_action', o: 'like', v: `%${d.cause_action}%` })
  }
  if (typeof d.occupation === 'string' && d.occupation.length > 0) {
    r.push({ k: 'a.occupation', o: 'like', v: `%${d.occupation}%` })
  }
  if (typeof d.processer === 'string' && d.processer.length > 0) {
    r.push({ k: 'cp.processer', o: 'like', v: `%${d.processer}%` })
  }
  return r
}

// 改变搜索条件
function changeSearch (d: { [k: string]: any }, params: {[k: string]: any}, setParams: (v: {[k: string]: any}) => void): void {
  if (d.year instanceof moment) {
    d.year = (d.year as Moment).year()
  }
  const keys = ['year', 'name', 'cause_action', 'occupation', 'processer']
  keys.forEach(key => {
    if (d[key] === undefined) {
      d[key] = undefined
    }
  })
  d.page = 1
  setParams({
    ...params,
    ...d
  })
}

function initForm (params: {[k: string]: any}, formRef: RefObject<FormInstance>): void {
  const c = formRef.current
  if (c === null) {
    return undefined
  }
  const o = qs.parse(qs.stringify(params))
  const r: { [k: string]: any } = {}
  if (typeof o.year === 'string') {
    r.year = o.year
  }
  if (typeof o.name === 'string') {
    r.name = o.name
  }
  if (typeof o.cause_action === 'string') {
    r.cause_action = o.cause_action
  }
  if (typeof o.occupation === 'string') {
    r.occupation = o.occupation
  }
  if (typeof o.processer === 'string') {
    r.processer = o.processer
  }
  c.setFieldsValue(r)
}

// 初始化案由树
async function initTree (setTreeData: (v: DataNode[]) => void): Promise<void> {
  const [e, d] = await awaitWrap(getTreeRequest())
  if (e === null && d !== null) {
    setTreeData(d)
  }
}

// 初始化职业分类
async function initOccupation (setOccupation: (v: string[]) => void): Promise<void> {
  const [e, d] = await awaitWrap(getOccupation())
  if (e === null && d instanceof Array) {
    setOccupation(d)
  }
}

// 初始化员工列表
async function initPersonList (setPersons: (v: string[]) => void): Promise<void> {
  const [e, d] = await awaitWrap(getPersonList())
  if (e === null && d instanceof Array) {
    setPersons(d)
  }
}

interface Props {
  params: {[k: string]: any}
  setParams: (v: {[k: string]: any}) => void
}

function Main ({params, setParams}: Props): ReactElement {
  const ref = useRef<FormInstance>(null)
  const [treeData, setTreeData] = useState<DataNode[]>([])
  const [occupation, setOccupation] = useState<string[]>([])
  const [persons, setPersons] = useState<string[]>([])
  const years: Array<string | number> = []
  for (let i = moment().year(); i >= 1996; i--) {
    years.push(i)
  }
  useEffect(() => {
    initTree(setTreeData).catch(e => console.error(e))
    initOccupation(setOccupation).catch(e => console.error(e))
    initPersonList(setPersons).catch(e => console.error(e))
  }, [])
  useEffect(() => {
    initForm(params, ref)
  }, [params])
  return (
    <div className={style.container}>
      <Form ref={ref} labelCol={{ flex: '80px' }} initialValues={{ year: moment().year() }} onFinish={d => changeSearch(d, params, setParams)} onReset={() => ref.current?.submit()}>
        <Row gutter={48}>
          <Col span={8}>
            <Item label='组庭年份' name='year'>
              <Select placeholder='请选择'>
                {years.map((li, i) => <Option key={i} value={li}>{li}</Option>)}
              </Select>
            </Item>
          </Col>
          <Col span={8}>
            <Item label='仲裁员名称' name='name'>
              <Input placeholder='请输入' />
            </Item>
          </Col>
          <Col span={8}>
            <Item label='职业分类' name='occupation'>
              <Select placeholder='请选择'>
                {occupation.map((li, i) => <Option key={i} value={li}>{li}</Option>)}
              </Select>
            </Item>
          </Col>
          <Col span={8}>
            <Item label='常办案由' name='cause_action'>
              <TreeSelect treeData={treeData} placeholder='请选择' showSearch />
            </Item>
          </Col>
          <Col span={8}>
            <Item label='配合秘书' name='processer'>
              <Select placeholder='请选择' showSearch allowClear>
                {persons.map((li, i) => <Option key={i} value={li}>{li}</Option>)}
              </Select>
            </Item>
          </Col>
          <Col span={8} className={style.btns}>
            <Space>
              <Button type='primary' htmlType='submit'>查询</Button>
              <Button htmlType='reset'>重置</Button>
            </Space>
          </Col>
        </Row>
      </Form>
    </div>
  )
}

export default Main
